<template>
  <div class="ReportTemplateMaintain">
    <el-dialog
      v-dialogDrag
      v-if="dialogObj.isShow"
      :title="dialogObj.title"
      :visible.sync="dialogObj.isShow"
      :close-on-click-modal="false"
      width="50%"
      destroy-on-close
      @close="dialogcel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="资源名称" prop="sourceName">
          <el-input v-model="form.sourceName" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="资源文件" prop="fileName">
          <el-upload
            ref="upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :limit="1"
            :on-success="uploadSuccess"
            :action="actionUrl"
            accept=".jpg, .png"
            multiple
            class="upload-demo">
            <el-button type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleDialog">关闭</el-button>
        <el-button type="primary" @click="confirmForm(isadd)">保存</el-button>
      </div>
    </el-dialog>
    <section class="layer">
      <div class="box">
        <div class="box-header">
          <span class="box-title">查询条件</span>
        </div>
        <div class="box-body">
          <el-form ref="searchForm" :model="searchForm" label-width="60px">
            <el-row :gutter="12">
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="资源名称" prop="sourceName" class="clearmargin" label-width="90px">
                  <el-input v-model="searchForm.sourceName" clearable placeholder="请输入" style="width:100%;" />
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8" :xl="6" style="float: right; text-align: right">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="search">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </section>
    <section class="layer">
      <div class="box">
        <div class="box-header handle">
          <span class="box-title">资源列表</span>
          <div class="box-tools">
            <el-button type="success" @click="addNewList">新增</el-button>
          </div>
        </div>
        <div class="box-body">
          <el-table
            v-loading="loading"
            :data="tableData"
            element-loading-spinner="el-loading1"
            height="stying"
            border
            style="width: 100%;">
            <el-table-column type="index" width="60" label="序号" align="center" />
            <el-table-column :show-overflow-tooltip="true" prop="sourceName" label="资源名称" width="260" align="center" />
            <el-table-column :show-overflow-tooltip="true" prop="image" label="缩略图" width="80" align="center">
              <template slot-scope="scope">
                <div class="table-img-box">
                  <img :src="scope.row.sourceUrl" alt class="table-img">
                </div>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="sourceUrl" label="URL" min-width="260" align="left">
              <template slot-scope="scope">
                <el-tag
                  v-clipboard:copy="scope.row.sourceUrl"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  class="copy-button"
                  type="success"
                  disable-transitions>复制</el-tag>
                &nbsp;&nbsp;&nbsp;{{ scope.row.sourceUrl }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button class="delete" type="text" @click.stop="deleteRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[15, 30, 50, 100]"
            :page-size="pageSize"
            :total="total"
            layout="slot, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange">
            <template slot>
              <span class="el-pagination__total">{{ `总共${total}条 显示${startRow}-${endRow}条` }}</span>
            </template>
          </el-pagination>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import {
  sourceUpdate,
  sourceGetAllPage,
  sourceDelete,
  sourceAdd
} from '@/api/resource-management'
export default {
  name: 'ReportTemplateMaintain',
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      actionUrl: `${process.env.BASE_API}/report-server/reportSourceController/upload.action`,
      // actionUrl: `http://172.16.41.111:8080/report-server/reportSourceController/upload.action`,
      fileList: [],
      searchForm: {
        sourceName: '',
        sourceUrl: ''
      },
      tableData: [],
      loading: false,
      modelTypeList: [], // 指标采集模版编码列表sourceName
      reportID: '',
      dialogObj: {
        isShow: false,
        title: '资源添加',
        rows: []
      },
      rules: {
        sourceName: [{
          required: true,
          message: '请输入资源名称',
          trigger: 'blur'
        }],
        fileName: [{
          required: true,
          message: '请上传资源文件',
          trigger: ['blur']
        }]
      },
      form: {
        sourceName: '',
        fileName: ''
      },
      // 总条数
      total: 0,
      startRow: 0,
      endRow: 0,
      // 每页多少条
      pageSize: 15,
      // 当前页
      currentPage: 1,
      isadd: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getTableData()
  },
  mounted() {},
  methods: {
    // 复制成功时的回调函数
    onCopy(e) {
      this.$message({
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<strong>操作成功</strong><p>内容已复制到剪切板</p>`,
        duration: 3000
      })
    },
    // 复制失败时的回调函数
    onError(e) {
      this.$alert(
        `<div class="myalert-header">操作失败</div>
                <div class="myalert-content">抱歉，复制失败</div>`, {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          type: 'error'
        }
      )
    },
    cancleDialog() {
      this.dialogObj.isShow = false
      this.fileList = []
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        // 上传成功后传参数到父组件中
        this.fileList.push({
          name: response.data
        })
        this.form.fileName = response.data
        this.$refs['form'].validateField('fileName')
        this.$message({
          type: 'success',
          dangerouslyUseHTMLString: true,
          message: `<strong>操作成功</strong><p>${response.message}</p>`,
          duration: 3000
        })
        // this.$options.methods.clearFiles()
      } else {
        this.$alert(
          `<div class="myalert-header">操作失败</div>
          <div class="myalert-content">${response.message}</div>`, {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            type: 'error'
          }
        )
        this.$refs.upload.uploadFiles.map((item, index) => {
          if (item.uid === file.uid) {
            this.$refs.upload.uploadFiles.splice(index, 1)
          }
        })
      }
    },
    handleRemove(file, fileList) {
      this.form.fileName = ''
      this.fileList = []
      this.$refs['form'].validateField('fileName')
    },
    handlePreview(file) {
      console.log(file)
    },
    // 上传之前
    beforeUpload(file) {
      console.log(file)
      let fileSize = file.size
      if (fileSize > 524288) {
        this.$alert(
          `<div class="myalert-header">操作失败</div>
          <div class="myalert-content">文件大小不能超过500kb</div>`, {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            type: 'error'
          }
        )
        return false
      }
      let type = file.name.split('.')
      let fileType = type[type.length - 1]
      let reg = /png|jpg/gi
      if (!reg.test(fileType)) {
        this.$alert(
          `<div class="myalert-header">操作失败</div>
          <div class="myalert-content">文件类型错误，允许上传文件类型：png,jpg</div>`, {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            type: 'error'
          }
        )
        return false
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 获取下拉数据
    // 查询
    search() {
      this.currentPage = 1
      this.getTableData()
    },
    // 新增
    addNewList() {
      this.isadd = true
      this.dialogObj.isShow = true
      this.dialogObj.title = '新增资源'
      this.form.fileName = ''
      this.form.sourceName = ''
      this.form.sourceUrl = ''
    },
    // 重置
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.search()
    },
    dialogcel() {
      this.$refs['form'].resetFields()
    },
    // 删除信息
    deleteRow(row) {
      this.$confirm(
        `<div class="myalert-header">操作提醒</div><div class="myalert-content">您进行的是删除操作, 是否继续?</div></div>`, {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(_ => {
          let params = row.sourceId
          sourceDelete(params)
            .then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  dangerouslyUseHTMLString: true,
                  message: `<strong>操作成功</strong><p>${res.data.message}</p>`
                })
                this.getTableData()
              } else {
                this.$alert(
                  `<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                    confirmButtonText: '确定',
                    dangerouslyUseHTMLString: true,
                    type: 'error'
                  }
                )
              }
            })
            .catch(err => {
              console(err)
            })
        })
        .catch(_ => {})
    },
    confirmForm() {
      this.$refs['form'].validate(valid => {
        console.log(valid)
        if (valid) {
          if (this.isadd) {
            let params = {
              ...this.form,
              userId: ''
            }
            sourceAdd(params)
              .then(res => {
                if (res.data.code === 0) {
                  this.$message({
                    type: 'success',
                    dangerouslyUseHTMLString: true,
                    message: `<strong>操作成功</strong><p>${res.data.message}</p>`
                  })
                  this.currentPage = 1
                  this.dialogObj.isShow = false
                  this.fileList = []
                  this.getTableData()
                } else {
                  this.$alert(
                    `<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                      confirmButtonText: '确定',
                      dangerouslyUseHTMLString: true,
                      type: 'error'
                    }
                  )
                }
              })
              .catch(err => {
                this.dialog = false
                console.log(err)
              })
          } else {
            let params = {
              ...this.form,
              userId: ''
            }
            sourceUpdate(params)
              .then(res => {
                if (res.data.code === 0) {
                  this.$message({
                    type: 'success',
                    dangerouslyUseHTMLString: true,
                    message: `<strong>操作成功</strong><p>${res.data.message}</p>`
                  })
                  this.dialogObj.isShow = false
                  this.getTableData()
                } else {
                  this.$alert(
                    `<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                      confirmButtonText: '确定',
                      dangerouslyUseHTMLString: true,
                      type: 'error'
                    }
                  )
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        }
      })
    },
    // 分页查询
    getTableData() {
      let params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        ...this.searchForm
      }
      this.loading = true
      sourceGetAllPage(params).then(res => {
        if (res.data.code === 0) {
          this.tableData = res.data.data
          this.total = res.data.data.length
          const num1 = this.pageSize * (this.currentPage - 1) + 1
          const num2 =
              this.pageSize * this.currentPage > this.total
                ? this.total
                : this.pageSize * this.currentPage
          this.startRow = num1
          this.endRow = num2
          this.loading = false
        } else {
          this.$alert(res.data.message, {
            type: 'error',
            confirmButtonText: '确定'
          })
          this.loading = false
        }
      })
    },
    // 分页器
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },
    // 查看
    checkRow(row) {
      this.loading = true
    }
  }
}

</script>

<style scoped lang="scss">
  .copy-button {
    cursor: pointer;
  }

  .table-img-box {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .table-img {
    max-width: 50px;
    max-height: 30px;
  }

  .ReportTemplateMaintain {
    height: 100%;

    section:last-child {
      height: calc(100% - 108px);

      .el-row {
        height: 100%;

        .el-col {
          height: 100%;

          .box {
            height: 100%;

            .box-body {
              height: calc(100% - 40px);
            }
          }
        }
      }
    }
  }

</style>
